from flask import Flask, send_file, request
from gtts import gTTS
from tempfile import NamedTemporaryFile

app = Flask(__name__)


# 文本转语音转换接口
@app.route('/convert', methods=['POST'])
def convert():
    # 获取文本参数
    text = request.form.get('text')
    # 获取语言参数,默认中文
    lang = request.form.get('lang', 'zh')

    # 调用gTTS生成语音
    tts = gTTS(text=text, lang=lang)

    # 将语音保存为临时文件
    temp_file = NamedTemporaryFile(delete=False)
    tts.save(temp_file.name)

    # 返回语音文件
    return send_file(temp_file.name, mimetype='audio/mpeg')


if __name__ == '__main__':
    # 运行Flask app
    app.run(port=5000)
